<template>
  <div class="menu-manager">
    <div class="manager-header">
      <h1>菜单管理系统</h1>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-plus" @click="addRootNode">添加根节点</el-button>
        <el-button-group>
          <el-button icon="el-icon-caret-bottom" @click="expandAll">展开全部</el-button>
          <el-button icon="el-icon-caret-right" @click="collapseAll">折叠全部</el-button>
        </el-button-group>
      </div>
    </div>

    <div class="manager-content">
      <div class="tree-panel">
        <div class="search-box">
          <el-input
            placeholder="输入关键字进行过滤"
            v-model="filterText"
            clearable
            prefix-icon="el-icon-search"
            size="medium"
          ></el-input>
        </div>
        
        <div class="tree-container">
          <el-tree
            ref="menuTree"
            :data="menuData"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :draggable="true"
            :allow-drop="allowDrop"
            :allow-drag="allowDrag"
            @node-drop="handleDrop"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span class="node-content">
                <i :class="data.icon" v-if="data.icon"></i>
                <span class="node-label">{{ data.title }}</span>
                <el-tag v-if="data.alwaysShow" size="mini" type="success">始终显示</el-tag>
                <el-tag v-if="data.hidden" size="mini" type="info">隐藏</el-tag>
              </span>
              <span class="node-actions">
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-plus"
                  title="添加子节点"
                  @click="() => append(data)"
                ></el-button>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-edit"
                  title="编辑节点"
                  @click="() => edit(node, data)"
                ></el-button>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-delete"
                  title="删除节点"
                  @click="() => remove(node, data)"
                ></el-button>
              </span>
            </span>
          </el-tree>
        </div>
      </div>

      <div class="operation-panel">
        <div class="panel-section">
          <h3 class="section-title">操作说明</h3>
          <div class="operation-list">
            <div class="operation-item">
              <i class="el-icon-plus operation-icon"></i>
              <span>添加子节点</span>
            </div>
            <div class="operation-item">
              <i class="el-icon-edit operation-icon"></i>
              <span>编辑节点</span>
            </div>
            <div class="operation-item">
              <i class="el-icon-delete operation-icon"></i>
              <span>删除节点</span>
            </div>
            <div class="operation-item">
              <i class="el-icon-rank operation-icon"></i>
              <span>拖拽排序</span>
            </div>
          </div>
        </div>

        <div class="panel-section">
          <h3 class="section-title">菜单预览</h3>
          <div class="json-preview">
            <pre>{{ jsonData }}</pre>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      @close="resetForm"      
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="菜单名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入节点名称"></el-input>
        </el-form-item>
        <el-form-item label="菜单ID" prop="id" v-if="isEdit">
          <el-input v-model="form.id" disabled></el-input>
        </el-form-item>
          <el-form-item label="component" prop="component">
          <el-input v-model="form.component"  placeholder="请输入正确的component" ></el-input>
        </el-form-item>
          <el-form-item label="重定向" prop="redirect">
          <el-input v-model="form.redirect"  placeholder="请输入正确的redirect" ></el-input>
        </el-form-item>
        <el-form-item label="菜单图标">
          <el-select v-model="form.icon" placeholder="请选择图标" style="width: 100%">
            <el-option
              v-for="icon in iconOptions"
              :key="icon.value"
              :label="icon.label"
              :value="icon.value"
            >
              <span style="float: left">
                <i :class="icon.value"></i>
              </span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ icon.label }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="节点路径">
          <el-input v-model="form.path" placeholder="请输入节点路径"></el-input>
        </el-form-item>
        <!-- 新增的字段 -->
        <el-form-item label="始终显示">
          <el-switch
            v-model="form.alwaysShow"
            active-text="是"
            inactive-text="否">
          </el-switch>
        </el-form-item>
        <el-form-item label="隐藏菜单">
          <el-switch
            v-model="form.hidden"
            active-text="是"
            inactive-text="否">
          </el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveNode">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getMenuList,insert,deleteById,update } from '@/api/menu'
export default {
  name: 'MenuManager',
  data() {
    // 生成唯一ID
    const generateId = () => {
      return Date.now().toString(36) + Math.random().toString(36).substr(2);
    };
    
    return {
      filterText: '',
      menuData: [],
      dialogVisible: false,
      dialogTitle: '添加节点',
      isEdit: false,
      form: {
        id: '',
        title: '',
        icon: '',
        path: '',
        parent: "",
        alwaysShow: true, // 新增字段
        hidden: false,      // 新增字段
        component:"",
        redirect:""
      },
      rules: {
        title: [
          { required: true, message: '请输入节点名称', trigger: 'blur' }
        ]
      },
      currentNode: null,
      generateId: generateId,
      iconOptions: [
        { value: 'el-icon-menu', label: '菜单' },
        { value: 'el-icon-setting', label: '设置' },
        { value: 'el-icon-user', label: '用户' },
        { value: 'el-icon-s-custom', label: '角色' },
        { value: 'el-icon-lock', label: '权限' },
        { value: 'el-icon-document', label: '文档' },
        { value: 'el-icon-notebook-2', label: '文章' },
        { value: 'el-icon-folder', label: '分类' },
        { value: 'el-icon-s-data', label: '数据' },
        { value: 'el-icon-s-marketing', label: '营销' },
        { value: 'el-icon-s-platform', label: '平台' },
        { value: 'el-icon-s-claim', label: '声明' },
        { value: 'el-icon-s-opportunity', label: '机会' },
        { value: 'el-icon-s-order', label: '订单' },
        { value: 'el-icon-s-promotion', label: '促销' },
        { value: 'el-icon-s-home', label: '首页' },
        { value: 'el-icon-s-shop', label: '商店' },
        { value: 'el-icon-s-finance', label: '财务' },
        { value: 'el-icon-s-ticket', label: '票务' },
        { value: 'el-icon-s-management', label: '管理' },
        { value: 'el-icon-s-open', label: '打开' },
        { value: 'el-icon-s-release', label: '发布' },
        { value: 'el-icon-s-flag', label: '标志' },
        { value: 'el-icon-s-comment', label: '评论' },
        { value: 'el-icon-s-check', label: '检查' },
        { value: 'el-icon-s-close', label: '关闭' },
        { value: 'el-icon-s-fold', label: '折叠' },
        { value: 'el-icon-s-unfold', label: '展开' }
      ]
    };
  },
  computed: {
    jsonData() {
      return JSON.stringify(this.menuData, null, 2);
    }
  },
  watch: {
    filterText(val) {
      this.$refs.menuTree.filter(val);
    }
  },
  created(){
    this.getMenuList()
  },
  methods: {
    async getMenuList() {
      const res = await getMenuList()
      this.menuData = res.data
    },
    async insert(menu) {
      const res = await insert(menu)
      if(res.code===200){
        this.getMenuList()
        this.$message({
          message:res.message,
          type: 'success'
        });
      }
    },
      async update(menu) {
      const res = await update(menu)
      if(res.code===200){
        this.getMenuList()
        this.$message({
          message:res.message,
          type: 'success'
        });
      }
    },
      async deleteById(id) {
      const res = await deleteById(id)
      if(res.code===200){
        this.getMenuList()
        this.$message({
          message:res.message,
          type: 'success'
        });
      }
    },
    // 过滤节点
    filterNode(value, data) {
      if (!value) return true;
      return data.title.indexOf(value) !== -1;
    },
    
    // 添加根节点
    addRootNode() {
      this.dialogTitle = '添加根节点';
      this.isEdit = false;
      this.currentNode = null;
      this.dialogVisible = true;
    },
    
    // 添加子节点
    append(data) {
      this.dialogTitle = '添加子节点';
      this.isEdit = false;
      this.currentNode = data;
      this.dialogVisible = true;
    },
    
    // 编辑节点
    edit(node, data) {
      this.dialogTitle = '编辑节点';
      this.isEdit = true;
      this.currentNode = node;
      this.form.id = data.id;
       this.form.component = data.component;
         this.form.redirect = data.redirect;
      this.form.title = data.title;
      this.form.icon = data.icon || '';
      this.form.path = data.path || '';
      this.form.alwaysShow = data.alwaysShow || false; // 新增字段
      this.form.hidden = data.hidden || false;         // 新增字段
      this.dialogVisible = true;
      
    },
    
    // 删除节点
    remove(node, data) {
      this.$confirm('此操作将永久删除该节点, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log("node===",node)
         console.log("data===",data)
        this.deleteById(data.id)
        // const parent = node.parent;
        // const children = parent.data.children || parent.data;
        // const index = children.findIndex(d => d.id === data.id);
        // children.splice(index, 1);
        // this.$message({
        //   type: 'success',
        //   message: '删除成功!'
        // });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    
    // 保存节点
    saveNode() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            // 编辑节点
            this.currentNode.data.title = this.form.title;
            this.currentNode.data.icon = this.form.icon;
            this.currentNode.data.path = this.form.path;
            this.currentNode.data.alwaysShow = this.form.alwaysShow; 
            this.currentNode.data.hidden = this.form.hidden;   
             this.currentNode.data.component = this.form.component; 
             this.currentNode.data.redirect = this.form.redirect;       
            this.update( this.currentNode.data)
          } else {
            // 添加节点
            const newNode = {
              id: this.generateId(),
              title: this.form.title,
              icon: this.form.icon,
              path: this.form.path,
              name: this.form.name,
              parent: null,
              component:this.form.component,
              alwaysShow: this.form.alwaysShow, // 新增字段
              hidden: this.form.hidden,        // 新增字段
              redirect:this.form.redirect
            };
            
            if (this.currentNode) {
              console.log("this.currentNode========", this.currentNode)
              newNode.parent = this.currentNode.id
              this.insert(newNode)
            } else {
              this.insert(newNode)
            }
          }
          
          this.dialogVisible = false;
        }
      });
    },
    
    // 重置表单
    resetForm() {
      this.form = {
        id: '',
        title: '',
        icon: '',
        path: '',
        parent: "",
        alwaysShow: false, // 新增字段
        hidden: false      // 新增字段
      };
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },
    
    // 展开全部
    expandAll() {
      this.$refs.menuTree.store._getAllNodes().forEach(node => {
        node.expanded = true;
      });
    },
    
    // 折叠全部
    collapseAll() {
      this.$refs.menuTree.store._getAllNodes().forEach(node => {
        node.expanded = false;
      });
    },
    
    // 拖拽放置验证
    allowDrop(draggingNode, dropNode, type) {
      // 不允许放置在内部分
      if (type === 'inner') {
        return true;
      } else {
        // 同级别拖拽
        return draggingNode.parent === dropNode.parent;
      }
    },
    
    // 拖拽节点验证
    allowDrag(draggingNode) {
      return true;
    },
    
    // 处理拖拽完成
    handleDrop(draggingNode, dropNode, dropType, ev) {
      this.$message({
        type: 'success',
        message: '排序成功!'
      });
    }
  }
};
</script>

<style scoped>
.menu-manager {
  height: 100vh;
  padding: 20px;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.manager-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.manager-header h1 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 500;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.manager-content {
  display: flex;
  flex: 1;
  gap: 20px;
}

.tree-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.search-box {
  margin-bottom: 15px;
}

.tree-container {
  flex: 1;
  overflow: auto;
}

.operation-panel {
  width: 320px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.panel-section {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.section-title {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  color: #303133;
  font-weight: 500;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.operation-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.operation-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 0;
}

.operation-icon {
  color: #409eff;
  font-size: 16px;
  width: 20px;
}

.json-preview {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
  max-height: 300px;
  overflow: auto;
}

.json-preview pre {
  margin: 0;
  font-size: 12px;
  line-height: 1.5;
  color: #606266;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.node-content {
  display: flex;
  align-items: center;
  gap: 6px;
}

.node-label {
  color: #606266;
}

.node-actions {
  display: flex;
  gap: 5px;
  opacity: 0;
  transition: opacity 0.3s;
}

.custom-tree-node:hover .node-actions {
  opacity: 1;
}

.node-actions .el-button {
  padding: 4px;
  height: auto;
}

/* 美化树形结构 */
::v-deep .el-tree {
  background-color: transparent;
}

::v-deep .el-tree-node__content {
  height: 36px;
  border-radius: 4px;
  margin-bottom: 2px;
}

::v-deep .el-tree-node__content:hover {
  background-color: #f5f7fa;
}

::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #ecf5ff;
}

::v-deep .el-tree-node__expand-icon {
  color: #c0c4cc;
  font-size: 16px;
}

::v-deep .el-tree-node__expand-icon.expanded {
  transform: rotate(0);
}

::v-deep .el-tree-node__expand-icon.is-leaf {
  color: transparent;
}
</style>